<template>
  <ele-page
    flex-table
    :multi-card="false"
    hide-footer
    style="min-height: 420px"
  >
    <!-- 搜索表单 -->
    <order-search
      @search="reload"
      :cache-key="getCurrentInstance().type.name"
    />
    <ele-card
      :body-style="{ paddingTop: '8px' }"
      flex-table
      :multi-card="false"
    >
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="id"
        :pagination="pagination"
        :loading="loading"
        flex-table
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        v-model:selections="selections"
        :highlight-current-row="true"
        :tools="['reload', 'export', 'size', 'columns', 'maximized']"
        :export-config="{
          fileName: '订单数据',
          // datasource: exportSource,
          tableName: getCurrentInstance().type.name,
        }"
        :print-config="{ datasource: exportSource }"
        :cache-key="getCurrentInstance().type.name"
      >
        <template #toolbar>
          <el-button
            type="danger"
            class="ele-btn-icon"
            :icon="DeleteOutlined"
            @click="action('remove')"
          >
            批量删除
          </el-button>

          <ExportButton
            :export-config="{
              fileName: '后台用户数据',
              tableName: 'SystemUserTable',
            }"
          >
            <template #button> 导出用户数据 </template>
          </ExportButton>
        </template>
        <template #organization="{ row }">
          <div>
            部门:
            <ele-copyable>{{
              row?.manager?.organization?.organization_name
            }}</ele-copyable>
          </div>

          <div>
            工号:
            <ele-copyable>{{ row?.job_number }}</ele-copyable>
          </div>

          <div>
            员工:
            <ele-copyable>{{ row?.manager?.nickname }}</ele-copyable>
          </div>
        </template>

        <template #company_name="{ row }">
          <div>公司名称:</div>
          <div>
            {{ row?.business?.company_name }}
          </div>
          <div>企业信用代码:</div>
          <div>
            {{ row?.business?.company_code }}
          </div>
        </template>
        <template #business="{ row }">
          <div>
            公司名称:
            {{ row?.business?.company_name }}
          </div>
        </template>

        <template #order_number="{ row }">
          <div>订单编号:</div>
          <div>
            {{ row?.order_number }}
          </div>
          <div>支付单号:</div>
          <div>
            {{ row?.pay?.pay_order_number }}
          </div>
        </template>

        <template #legal_person="{ row }">
          <div>法人:{{ row?.business?.legal_person }}</div>

          <div>手机号:{{ row?.additional?.legal_person_phone }}</div>
          <div>身份证号:{{ row?.additional?.legal_person_id_card }}</div>
        </template>

        <template #annual_turnover="{ row }">
          <div>年营业额:{{ row?.additional?.annual_turnover }}万元</div>

          <div>纳税额:{{ row?.additional?.tax_amount }}万元</div>
        </template>

        <template #status="{ row }">
          <dict-data :code="'order_status'" v-model="row.status" type="tag" />
        </template>

        <template #action="{ row }">
          <!-- <el-link type="primary" underline="never"> 待开发 </el-link> -->

          <el-link
            type="primary"
            underline="never"
            :disabled="row.status != 2"
            @click="action('confirm', row)"
          >
            完成
          </el-link>
          <el-divider direction="vertical" />
          <el-link
            type="primary"
            underline="never"
            target="_blank"
            :href="API_BASE_URL + 'search/scrip?id=' + row.id"
          >
            查看凭证
          </el-link>
          <el-divider direction="vertical" />

          <ele-dropdown
            :items="[
              { title: '入款登记', command: 'paylog' },
              { title: '编辑', command: 'edit' },
              {
                title: '删除',
                command: 'delete',
                danger: true,
                divided: true,
              },
            ]"
            style="display: inline"
            @command="(key) => dropClick(key, row)"
          >
            <el-link type="primary" underline="never">
              <span>更多</span>
              <el-icon
                :size="12"
                style="vertical-align: -1px; margin-left: 2px"
              >
                <ArrowDown />
              </el-icon>
            </el-link>
          </ele-dropdown>
          <!-- 
          <el-link type="primary" underline="never" @click="openEdit(row)">
            修改
          </el-link>
          <el-divider direction="vertical" />
          <el-link
            type="danger"
            underline="never"
            :disabled="row.status != 1"
            @click="action('remove', row)"
          >
            删除
          </el-link> -->
        </template>
      </ele-pro-table>
    </ele-card>

    <ele-image-viewer
      v-model="showImageViewer"
      :urlList="viewerImages"
      :initialIndex="viewerIndex"
      :infinite="false"
      :hide-on-click-modal="true"
    />

    <!-- 修改 -->
    <order-edit
      action="edit"
      :data="current"
      v-model="showEdit"
      @done="reload"
    />

    <!-- 修改 -->
    <order-paylog
      action="paylog"
      :data="current"
      v-model="showPayLog"
      @done="reload"
    />
  </ele-page>
</template>

<script setup>
import { ref, getCurrentInstance } from "vue";

import { DeleteOutlined } from "@/components/icons";
import OrderSearch from "./components/order-search.vue";
import OrderEdit from "./components/order-edit.vue";
import OrderPaylog from "./components/order-paylog.vue";
import { ArrowDown } from "@/components/icons";
import ExportButton from "@/components/ExportButton/index.vue";
import {
  pageOrders,
  removeOrders,
  listOrders,
  confirmOrders,
} from "@/api/order/order";
import { API_BASE_URL } from "@/config/setting";

import { useOperator } from "@/hooks/operator";

import { useTable } from "@/hooks/useTable";
import { useModal } from "@/hooks/useModal";

defineOptions({ name: "OrderOrderTable" });

/** 是否打开图片预览 */
const showImageViewer = ref(false);

/** 图片预览数据 */
const viewerImages = ref([]);

/** 图片预览初始位置 */
const viewerIndex = ref(0);

/** 表格列配置 */
const columns = ref([
  {
    type: "selection",
    columnKey: "selection",
    width: 50,
    align: "center",
    fixed: "left",
  },
  {
    prop: "organization",
    label: "员工信息",
    width: 170,
    fixed: "left",
    copy: true,

    slot: "organization",
    formatter: (row) => {
      let str = "";
      str += "部门:" + (row?.manager?.organization?.organization_name ?? "");
      str += "工号:" + (row?.job_number ?? "");
      str += "员工:" + (row?.manager?.nickname ?? "");
      return str;
    },
  },

  {
    prop: "company_name",
    label: "企业信息",
    width: 170,
    fixed: "left",
    copy: true,
    slot: "company_name",
    formatter: (row) => {
      let str = "";
      str += "企业名称:" + (row?.business?.company_name ?? "");
      str += "企业信用代码:" + (row?.business?.company_code ?? "");
      return str;
    },
  },

  {
    prop: "business.legal_person",
    label: "法人信息",
    minWidth: 180,
    slot: "legal_person",
    copyOnly: true,
    formatter: (row) => {
      let str = "";
      str += "法人:" + (row?.business?.legal_person ?? "");
      str += "手机号:" + (row?.additional?.legal_person_phone ?? "");
      str += "身份证号:" + (row?.additional?.legal_person_id_card ?? "");
      return str;
    },
  },

  {
    prop: "annual_turnover",
    label: "年营业额信息",
    minWidth: 120,
    slot: "annual_turnover",
    copy: true,
    formatter: (row) => {
      return row?.additional?.annual_turnover + "万元";
    },
  },
  {
    prop: "business.province",
    label: "省份",
    minWidth: 120,
    copy: true,
  },
  {
    prop: "product_name",
    label: "服务内容",
    minWidth: 120,
    copy: true,
    showOverflowTooltip: false,
    formatter: (row) => {
      return row?.entry
        .map(function (item) {
          return item.product_name;
        })
        .join(",");
    },
  },
  {
    prop: "total_price",
    label: "金额",
    minWidth: 120,
    copy: true,
  },
  {
    prop: "pay.refund_price",
    label: "退款金额",
    minWidth: 120,
    copy: true,
  },
  {
    prop: "order_number",
    label: "订单编号",
    minWidth: 140,
    copy: true,
    showOverflowTooltip: false,
    slot: "order_number",
  },
  {
    prop: "pay_time",
    label: "支付时间",
    copy: true,
    minWidth: 120,
  },
  {
    prop: "create_time",
    label: "创建时间",
    copy: true,
    minWidth: 120,
  },
  {
    prop: "status",
    label: "订单状态",
    sortable: "custom",
    copy: true,
    minWidth: 80,
    slot: "status",
    fixed: "right",
  },
  {
    columnKey: "action",
    label: "操作",
    width: 200,
    fixed: "right",
    align: "center",
    slot: "action",
    hideInPrint: true,
    hideInExport: true,
  },
]);

/** 导出和打印全部数据的数据源 */
const exportSource = ({ where, orders }) => {
  return listOrders({ ...where, ...orders });
};

const {
  loading,
  pagination,
  tableRef,
  datasource,
  reload,
  current,
  selections,
} = useTable({
  getPages: pageOrders,
  beforeQuery: (params) => {
    // 可以修改或添加查询参数
    console.log("查询参数:", params); // 调试用，实际不需要这一行
    return {
      ...params,
      ...params.where,
    };
  },
});

const { visible: showEdit, open: openEdit } = useModal({
  beforeOpen: async (row) => {
    current.value = row; // 设置当前行数据
    // if (!row?.editable) {
    //   throw new Error("没有编辑权限");
    // }
  },
});

const { visible: showPayLog, open: openPayLog } = useModal({
  beforeOpen: async (row) => {
    current.value = row; // 设置当前行数据
    // if (!row?.editable) {
    //   throw new Error("没有编辑权限");
    // }
  },
});

/** 下拉菜单点击事件 */
const dropClick = (key, row) => {
  if (key === "edit") {
    openEdit(row);
  } else if (key === "delete") {
    action("remove", row);
  } else if (key === "paylog") {
    openPayLog(row);
  }
};

/** 删除 */
// 替换原有的remove方法
const { action } = useOperator({
  actionConfigs: {
    remove: {
      title: "删除",
      confirmText: "确定要删除{%s}这些数据吗?",
      api: removeOrders,
      beforeSubmit: (params) => {
        // 可以修改或添加提交参数
        console.log("[DEBUG] beforeSubmit 钩子被调用", params);
        return params; // 必须返回处理后的参数
      },
    },
    confirm: {
      title: "完成订单",
      confirmText: "确定要完成为{%s}这些数据吗?",
      api: confirmOrders,
      // skipConfirm: true,
      beforeSubmit: (params) => {
        // 可以修改或添加提交参数
        // const status = checked ? 0 : 1;
        console.log("[DEBUG] beforeSubmit 钩子被调用", params);
        return params; // 必须返回处理后的参数
      },
    },
  },
  selections,
  reload,
  idField: "id",
  idName: "order_number",
});
</script>
